package com.cdu.ai_intelligent_teaching_and_training_system.service;

import com.cdu.ai_intelligent_teaching_and_training_system.entity.User;
import com.cdu.ai_intelligent_teaching_and_training_system.mapper.UserMapper;
import com.cdu.ai_intelligent_teaching_and_training_system.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtil jwtUtil;

    public java.util.Optional<User> findByUsername(String username) {
        User user = userMapper.selectByUsername(username);
        return java.util.Optional.ofNullable(user);
    }

    public java.util.Optional<User> findByEmail(String email) {
        User user = userMapper.selectByEmail(email);
        return java.util.Optional.ofNullable(user);
    }

    public User save(User user) {
        if (user.getUserId() == null) {
            userMapper.insert(user);
        } else {
            userMapper.update(user);
        }
        return user;
    }

    public boolean existsByUsername(String username) {
        return userMapper.countByUsername(username) > 0;
    }

    public boolean existsByEmail(String email) {
        return userMapper.countByEmail(email) > 0;
    }

    public boolean validatePassword(String rawPassword, String encodedPassword) {
        return rawPassword.equals(encodedPassword);
    }
}